package weaver.interfaces.gyxy.rabbitmq.config;

import com.rabbitmq.client.Channel;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * channel管理
 **/
public class RabbitMqChannelService {

    private RabbitMqChannelPool pool;

    public static RabbitMqChannelService getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 获取channel对象
     * pool.borrowObject()是线程安全的
     *
     * @return 结果
     * @throws Exception 异常
     */
    public Channel getChannel() throws Exception {
        return pool.borrowObject();
    }

    /**
     * 归还channel对象
     *
     * @param channel 结果
     */
    public void returnChannel(Channel channel) {
        pool.returnObject(channel);
    }

    private static class SingletonHolder {
        private final static RabbitMqChannelService INSTANCE = new RabbitMqChannelService();
    }

    private RabbitMqChannelService() {
        initPool();
    }

    /**
     * 初始化pool
     */
    private void initPool() {
        RabbitMqChannelPoolFactory factory = new RabbitMqChannelPoolFactory();
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        // 设置最大连接数
        config.setMaxTotal(300);
        // 最大空闲连接数
        config.setMaxIdle(20);
        // 最小空闲连接数
        config.setMinIdle(10);
        // 空闲连接检测周期
        config.setTimeBetweenEvictionRunsMillis(6000);
        // 达到此空闲时间后，连接将被移除
        config.setSoftMinEvictableIdleTimeMillis(20000);
        // 连接资源耗尽后最大等待时间
        config.setMaxWaitMillis(10000);

        pool = new RabbitMqChannelPool(factory, config);
    }
}
